package com.smart.common.shiro.controller;

import com.smart.common.shiro.exception.CustomShiroException;
import com.smart.common.shiro.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @PostMapping("login")
    public String login(String username, String password) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
        } catch (IncorrectCredentialsException e) {
            throw new CustomShiroException("账号或密码错误");
        } catch (ExcessiveAttemptsException e) {
            throw new CustomShiroException("操作过于频繁,请稍后在试!");
        }
        return ShiroUtils.getSession().getId().toString();
    }
}